package Thread;

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    //记录执行时间
    private long time;
    public MyTimerTask(Runnable task,long time) {
        this.task = task;
        this.time = time;
    }
    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(time - o.time);
    }
    public long getTime() {
        return time;
    }
    public void run() {
        task.run();
    }
}
//自己实现一个定时器
class MyTimer{
    private PriorityQueue<MyTimerTask> tasks=new PriorityQueue<MyTimerTask>();
    private Object locker=new Object();
    public void schedule(Runnable task,long delay){
        synchronized(locker){
            MyTimerTask timerTask=new MyTimerTask(task,System.currentTimeMillis()+delay);
            tasks.offer(timerTask);
            locker.notify();
        }
    }
    public MyTimer(){
    Thread t=new Thread(()->{
        try {
            while(true){
                synchronized(locker){
                    while(tasks.isEmpty()){
                        locker.wait();
                    }
                    MyTimerTask timerTask=tasks.peek();
                    if (System.currentTimeMillis()<timerTask.getTime()){
                        locker.wait(timerTask.getTime()-System.currentTimeMillis());
                    }else{
                        timerTask.run();
                        tasks.poll();
                    }
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
    t.start();
    }
}
public class Demo38 {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(()->{
            System.out.println("1000");
        },1000);
        myTimer.schedule(()->{
            System.out.println("2000");
        },2000);
        myTimer.schedule(()->{
            System.out.println("3000");
        },3000);
    }
}
